import {
	BASE_URL
} from '@/env.js'

export const dlingFun = () => {
	uni.showToast({
		title: '暂未开放...',
		icon: 'none'
	})
}

//图片路径拼接
export const fixedImg = (url) => {
	if (!url) return
	if (url.startsWith("http")) return url
	if (url.startsWith("/static")) return url
	return `https://${url}`
}

//图片预览   data    List<string>
export const preImg = (data) => {
	uni.previewImage({
		urls: data,
		longPressActions: {
			itemList: ['发送给朋友', '保存图片', '收藏'],
			success: function(data) {
				console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
			},
			fail: function(err) {
				console.log(err.errMsg);
			}
		}
	});
}
//图片预览(带索引，预览多张图片 自动定位点击的那张图片)   data    List<string>   current  可以是索引值 也可以是图片的url
export const preImgIndex = (data, index) => {
	uni.previewImage({
		current: index,
		urls: data,
		longPressActions: {
			itemList: ['发送给朋友', '保存图片', '收藏'],
			success: function(data) {
				console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
			},
			fail: function(err) {
				console.log(err.errMsg);
			}
		}
	});
}

/**
@desc 文件上传
@param {arr} 		Array 文件资源 [{uri,name},{uri,name},{uri,name}]
*/
export const loadFile = (arr) => {
	return new Promise((resolve, reject) => {
		var singleLoad = function(data) {
			return new Promise((res, rej) => {
				uni.uploadFile({
					url: UP_URL,
					filePath: data.uri,
					name: data.name,
					header: {
						"beauty-client": 3,
						"beauty-token": uni.getStorageSync("token")
					},
					success: (uploadFileRes) => {
						let resulut = JSON.parse(uploadFileRes.data)
						res(resulut)
					},
					fail: (e) => {
						rej(e);
					}
				})
			})
		}
		Promise.all(arr.map(item => singleLoad(item))).then(res => {
			resolve(res)
		}).catch(err => {
			reject(err)
		})
	})
}

//处理富文本里面的图片，将图片设置未富文本容器的宽度100%
export const getRichText = (details) => {
	if (!details) return '';
	// 处理图片之间的间隙
	let lastTexts = details;
	lastTexts = lastTexts.replaceAll('<img', '<img style="max-width:100%";height:auto;')
	console.log(lastTexts.indexOf('<p><img'));
	if (lastTexts.indexOf('<p><img') == 0) {
		console.log('进来了吗');
		lastTexts = lastTexts.replaceAll('<p><img', '<p style="font-size:0px;"><img')
	}
	console.log(lastTexts);
	return lastTexts
}

export const copy = (text) => {
	uni.setClipboardData({
		data: text,
		success: function() {
			console.log('success');
		}
	});
}


//打开地图导航
export const openMap = (data) => {
	var t = this
	uni.openLocation({
		latitude: data.lat,
		longitude: data.lng,
		success: function() {},
		fail(e) {
			if (e.errMsg.includes('auth deny')) openSetting("")
		}
	});
}

//打电话配置
export const phone = (data) => {
	if (!data) return
	uni.makePhoneCall({
		phoneNumber: `${data}`
	})
}

export const openSetting = (text) => {
	uni.showModal({
		title: '提示',
		content: text || '小程序申请打开您的权限配置',
		success: function(res) {
			if (res.confirm) {
				uni.openSetting({})
			}
		}
	});
}

// 价格处理
export const totalPrice = (val) => {
	let vals = '';
	vals = parseFloat(val).toFixed(2);
	return vals;
}


/**
 * 预览图片
 * @param {Array} urls 图片数组
 * @param {number} current 索引
 */
export const previewImage = (urls, current = 1) => {
	// 预览图片
	const list = urls;
	let imgList = [];
	list.forEach(item => {
		imgList.push(item);
	})

	uni.previewImage({
		urls: imgList,
		current,
		indicator: 'number',
		loop: true,
	})
}

/**
 * 单独预览图片
 * @param {string} imgUrl 图片地址
 */
export const previewImageAlone = (imgUrl) => {
	// 预览图片
	uni.previewImage({
		urls: [imgUrl],
		current: 0,
		indicator: 'number',
		loop: true,
	})
}

/**
 * 判断数据格式
 * @param {string} fileName 文件名 
 */
export const getFileType = (fileName) => {
	// 后缀获取
	let suffix = ''
	// 获取类型结果
	let result = ''
	try {
		const flieArr = fileName.split('.') //根据.分割数组
		suffix = flieArr[flieArr.length - 1] //取最后一个
	} catch (err) { //如果fileName为空等.split方法会报错，就走下面的逻辑
		suffix = ''
	}
	// fileName无后缀返回 0
	if (!suffix) { //走catch后返回false
		return 0
	}
	suffix = suffix.toLocaleLowerCase() //将后缀所有字母改为小写方便操作

	// 图片格式
	const imglist = ['png', 'jpg', 'jpeg'] //可以将符合该分类的后缀都写入数组里
	result = imglist.find(item => item === suffix)
	if (result) {
		return 1; //图片
	}
	// 视频格式
	const videolist = ['mp4', 'm2v', 'mkv', 'rmvb', 'wmv', 'avi', 'flv', 'mov', 'm4v']
	result = videolist.find(item => item === suffix)
	if (result) {
		return 2; //视频
	}
	/*  这里开始写入需要判断的逻辑体  */
	return 0 //以上的判断逻辑都没return时反馈当前后缀是其他类型文件后缀
}

/**
 * 时间戳转日期格式
 * @param {Object} timeStamp
 */
export const timeStampTurnTime = (timeStamp, type = "") => {
	if (timeStamp === 0 || timeStamp == null) {
		return ''
	} else {
		let date = new Date(parseInt(timeStamp))
		let y = date.getFullYear()
		let MM = date.getMonth() + 1
		MM = MM < 10 ? ('0' + MM) : MM
		let d = date.getDate()
		d = d < 10 ? ('0' + d) : d
		let h = date.getHours()
		h = h < 10 ? ('0' + h) : h
		let m = date.getMinutes()
		m = m < 10 ? ('0' + m) : m
		let s = date.getSeconds()
		s = s < 10 ? ('0' + s) : s
		if (type == 'y') return y;
		if (type == 'm') return MM;
		if (type == 'd') return d;
		if (type == 'all') return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
		if (type == 'handle') return y + '-' + MM + '-' + d + ' ' + h + ':' + m;
		else return y + '-' + MM + '-' + d;
	}
}


export const weekDay = (time) => {
	const weekNum = new Date(time).getDay();
	const week = {
		0: '周天',
		1: '周一',
		2: '周二',
		3: '周三',
		4: '周四',
		5: '周五',
		6: '周六'
	}

	return week[weekNum] ? week[weekNum] : '日期错误';
}


export const weekDayEn = (time) => {
	const weekNum = new Date(time).getDay()
	const week = {
		0: '',
		1: 'mondayTasteList',
		2: 'tuesdayTasteList',
		3: 'wednesdayTasteList',
		4: 'thursdayTasteList',
		5: 'fridayTasteList',
		6: 'saturdayTasteList'
	}
	// console.log(time, '看看日期', weekNum, week[weekNum]);
	return week[weekNum] ? week[weekNum] : '日期错误';
}


//   内容超过30个字后以...显示
export const ellipsis = (value, num = 12) => {
	if (!value) return '';
	if (typeof(value) == 'number') value = value.toString();
	if (value.length > num) {
		return value.slice(0, num) + '...'
	}
	return value
}

export const hideKeyboard = () => {
	uni.hideKeyboard()
}

// 获取指定值的索引
export const findValueIndex = (obj, value) => {
	return Object.values(obj).findIndex(val => val === value);
}